import json
import re
import logging

from meiduo001.utils.view import LoginRequiredMixin

logger = logging.getLogger('django')

from django.contrib.auth import login, authenticate, logout

from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from users.models import User, Address


class UsernameCountView(View):

    def get(self, request, username):
        '''用户名重复注册'''
        try:
            count = User.objects.filter(username=username).count()
        except Exception as e:
            return JsonResponse({'code': 400,
                                 'errmsg': '无法访问数据库'})
        return JsonResponse({'code': 0,
                             'errmsg': 'ok',
                             'count': count})


class MobileCountView(View):
    def get(self, request, mobile):
        '''手机号重复注册'''
        try:
            count = User.objects.filter(mobile=mobile).count()
        except Exception as e:
            return JsonResponse({'code': 400,
                                 'errmsg': '无法访问数据库'})
        return JsonResponse({'code': 0,
                             'errmsg': 'ok',
                             'count': count})


class RegisterView(View):
    def post(self, request):
        dict = json.loads(request.body)
        username = dict.get('username')
        password = dict.get('password')
        password2 = dict.get('password2')
        mobile = dict.get('mobile')
        sms_code_client = dict.get('sms_code')
        allow = dict.get('allow')

        if not all([username, password, password2, mobile, sms_code_client, allow]):
            return JsonResponse({'code': 400,
                                 'errmsg': '缺少必要参数'})

        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return JsonResponse({'code': 400,
                                 'errmsg': 'username格式有误'})
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return JsonResponse({'code': 400,
                                 'errmsg': 'password格式有误'})
        if password != password2:
            return JsonResponse({'code': 400,
                                 'errmsg': '两次输入不对'})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400,
                                 'errmsg': 'mobile格式有误'})
        if allow != True:
            return JsonResponse({'code': 400,
                                 'errmsg': 'allow格式有误'})
        redis_conn = get_redis_connection('verify_code')
        try:
            sms_code_server = redis_conn.get('sms_%s' % mobile)
        except Exception as e:
            return JsonResponse({'code': 400,
                                 'errmsg': '无法访问数据库'})

        if sms_code_server is None:
            return JsonResponse({'code': 400,
                                 'errmsg': '验证码过期'})

        if sms_code_client != sms_code_server.decode():
            return JsonResponse({'code': 400,
                                 'errmsg': '验证码输入错误'})
        try:
            user = User.objects.create_user(
                username=username,
                password=password,
                mobile=mobile, )
        except Exception as e:
            return JsonResponse({'code': 400,
                                 'errmsg': '无法访问数据库'})
        login(request, user)

        response = JsonResponse({'code': 0,
                                 'errmsg': 'ok'})
        response.set_cookie('username',
                            user.username,
                            max_age=3600 * 24 * 14)
        return response


class LoginView(View):
    def post(self, request):
        dict = json.loads(request.body)
        username = dict.get('username')
        password = dict.get('password')
        remembered = dict.get('remembered')

        if not all([username, password]):
            return JsonResponse({'code': 400,
                                 'errmsg': '缺少必要参数'})

        user = authenticate(username=username, password=password)
        if user is None:
            return JsonResponse({'code': 400,
                                 'errmsg': '用户名或密码错误'})
        login(request, user)

        if remembered != True:
            request.session.set_expiry(0)
        else:
            request.session.set_expiry(None)

        response = JsonResponse({'code': 0,
                                 'errmsg': 'ok'})
        response.set_cookie('username',
                            user.username,
                            max_age=3600 * 24 * 14)
        return response


class LogoutView(View):
    def delete(self, request):
        logout(request)

        response = JsonResponse({'code': 0,
                                 'errmsg': 'ok'})

        response.delete_cookie('username')
        return response


class UserInfoView(LoginRequiredMixin, View):
    '''个人中心'''

    def get(self, request):
        try:
            info_data = {'username': request.user.username,
                         'mobile': request.user.mobile,
                         'email': request.user.email,
                         'email_active': request.user.email_active}
        except  Exception as e:
            return JsonResponse({'code': 400,
                                 'errmsg': '无法打开数据库'})

        return JsonResponse({'code': 0,
                             'errmsg': 'ok',
                             'info_data': info_data})


class EmailView(View):
    '''添加邮箱'''

    def put(self, request):
        dict = json.loads(request.body)
        email = dict.get('email')
        if not email:
            return JsonResponse({'code': 400,
                                 'errmsg': '缺少必要参数'})
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return JsonResponse({'code': 400,
                                 'errmsg': 'emial格式有误'})
        try:
            request.user.create(email=email)
            request.user.save()
        except Exception as e:
            return JsonResponse({'code': 400,
                                 'errmsg': 'email保存失败'})
        # 发送验证短信
        verify_url = request.user.generate_verify_email_url
        from celery_tasks.email.tasks import send_verify_email
        send_verify_email.delay(email, verify_url)
        return JsonResponse({'code': 0,
                             'errmsg': 'ok'})


class VerifyEmailView(View):
    """验证邮箱"""

    def put(self, request):
        token = request.GET.get('token')
        if not token:
            return JsonResponse({'code': 400,
                                 'errmsg': '缺少必要参数'})
        user = request.user.check_verify_email_token(token)
        if not user:
            return JsonResponse({'code': 400,
                                 'errmsg': '无效token值'})
        try:
            user.email_active = True
            user.save()
        except Exception as e:
            return JsonResponse({'code': 400,
                                 'errmsg': '修改失败'})
        return JsonResponse({'code': 0,
                             'errmsg': 'ok'})


class CreateAddressView(View):
    '''新增地址'''

    def post(self, request):
        try:
            count = Address.objects.filter(user=request.user,
                                           is_deleted=False).count()
        except Exception as e:
            return JsonResponse({'code': 400,
                                 'errmsg': '获取地址数据出错'})
            # 判断是否超过地址上限：最多20个
        if count >= 20:
            return JsonResponse({'code': 400,
                                 'errmsg': '超过地址数量上限'})



        dict = json.loads(request.body)
        receiver = dict.get('receiver')
        province_id = dict.get('province_id')
        city_id = dict.get('city_id')
        district_id = dict.get('district_id')
        place = dict.get('place')
        mobile = dict.get('mobile')
        tel = dict.get('tel')
        email = dict.get('email')

        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 400,
                                 'errmsg': '缺少必要参数'})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400,
                                 'errmsg': '参数mobile有误'})

        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return JsonResponse({'code': 400,
                                     'errmsg': '参数tel有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return JsonResponse({'code': 400,
                                     'errmsg': '参数email有误'})

        try:
            address = Address.objects.create(
                user=request.user,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                title=receiver,
                receiver=receiver,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email)
            # 设置地址信息
            if not request.user.default_address:
                request.user.default_address = address
                request.user.save()
        except Exception as e:
            return JsonResponse({'code': 400,
                                 'errmsg': '保存数据失败'})

        address = [
            {
                'id': address.id,
                "title": address.title,
                'receiver': address.receiver,
                'province': address.province.name,
                'city': address.city.name,
                'district': address.district.name,
                'place': address.place,
                'mobile': address.mobile,
                'tel': address.tel,
                'email': address.email,

            }
        ]
        return JsonResponse({'code': 0,
                             'errmsg': 'ok'})
